import fitz
import os
from PIL import Image
from PIL import ImageFile
from PIL import ImageDraw
from PIL import ImageFont

ImageFile.LOAD_TRUNCATED_IMAGES = True
Image.MAX_IMAGE_PIXELS = None


# PDF转图片
def pdf2img(pdf_path, img_path, zoom_x, zoom_y, rotation_angle):
    pdf = fitz.open(pdf_path)
    for pg in range(0, pdf.pageCount):
        page = pdf[pg]
        trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotation_angle)
        pm = page.getPixmap(matrix=trans, alpha=False)
        # 开始写图像
        pm.writePNG(img_path + str("{0:03d}".format(pg + 1)) + ".png")
    pdf.close()


# 图片合并为PDF
def img2pdf(folder_path, save_path):
    files = os.listdir(folder_path)
    doc = fitz.open()
    for file in files:
        print(folder_path + file)
        imgdoc = fitz.open(folder_path + file)
        pdfbytes = imgdoc.convertToPDF()
        pdf_name = file.split(".")[0] + '.pdf'
        imgpdf = fitz.open(pdf_name, pdfbytes)
        doc.insertPDF(imgpdf)
    doc.save(save_path)


# 图片上添加页码
def img_draw_text(folder_path, save_path):
    files = os.listdir(folder_path)
    count = 1
    for file in files:
        print("image---->" + folder_path + file)
        img = Image.open(folder_path + file)
        size = img.size
        width = size[0] - 140
        height = size[1] - 64
        draw = ImageDraw.Draw(img)
        ft = ImageFont.truetype(r"E:\limh\pdf2image\simsun.ttc", 14)
        draw.text((width, height), str(count), fill='black', font=ft)
        img.save(save_path + file)
        count += 1


# pdf2img(r"E:\limh\pdf2image\11.pdf", r"C:\Users\limh\Desktop\image\\", 1.5, 1.5, 0)
img2pdf(r"C:\Users\limh\Desktop\file\\", r"E:\limh\pdf2image\result.pdf")
# img_draw_text(r"E:\limh\pdf2image\image\\", r"C:\Users\limh\Desktop\file\\")
